package com.four.bmm.controller;

import com.four.bmm.entity.News;
import com.four.bmm.service.NewsService;
import com.four.bmm.util.PageUtil;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/GetAllNewsServlet")
public class GetAllNewsServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        NewsService newsService = new NewsService();
        String keyword = request.getParameter("keyword");
        String pageno1 = request.getParameter("pageno");
        if (pageno1 == null) {
            pageno1 = "1";
        }
        int pageno = Integer.parseInt(pageno1);
        int sumnews = newsService.NewsCount(keyword);
        int sumpages = PageUtil.getToatlPages(sumnews);
        if (pageno < 1) {
            pageno = 1;
        }
        if (pageno > sumpages) {
            pageno = sumpages;
        }
        List<News> newsList = newsService.GetAllNews(pageno, keyword);
        if (newsList.size() != 0) {
            HttpSession session = request.getSession();
            session.setAttribute("keyword", keyword);
            request.setAttribute("sumnews", sumnews);
            request.setAttribute("pageno", pageno);
            request.setAttribute("sumpages", sumpages);
            request.setAttribute("newsList", newsList);
            request.getRequestDispatcher("TestGetNews.jsp").forward(request, response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
